<template>
  <div class="Box">
    <!-- 顶部搜索/添加 -->
    <div class="SearchBox flex-LAR" v-show="tableData.length >= 0">
      <el-input v-model="SearchKeyWord.searchValue" placeholder="请输入搜索内容" class="input-with-select"
        @keyup.enter="SearchRouteList">
        <template #prepend>
          <el-select v-model="SearchKeyWord.selectKey" style="width: 6.25rem">
            <el-option v-for="(item, index) in SearcSelect" :key="index" :label="item.label" :value="item.prop" />
          </el-select>
        </template>
        <template #append>
          <el-button class="searchBtn" :icon="Search" @click="SearchRouteList" />
        </template>
      </el-input>
      <el-button class="addBtn" type="primary" :icon="Plus" @click="handleAdd" />
    </div>
    <!-- 分页 -->
    <div class="PageBox">
      <el-pagination :hide-on-single-page="true" v-model:current-page="page.currentPage" v-model:page="page.pageNum"
        v-model:limit="page.pageSize" v-model:total="page.total" :page-count="Math.ceil(page.total / page.pageSize)" />
    </div>
    <!-- 表格 -->
    <div class="TableBox">
      <cy-table class="Table" row-key="route_id" :data="tableData" :columns="ruleTable.columns" :loading="loading"
        @selection-change="handleSelectionChange" />
    </div>
    <!-- 修改抽屉 -->
    <el-drawer v-model="editdrawer" title="edit" :with-header="false">
      <cy-form class="EditForm" label-width="auto" style="max-width: 31.25rem">
        <cy-form-item v-for="(item, index) in editFormColumns" :key="index" :label="item.label">
          <!--状态选择 -->
          <template v-if="['status'].includes(item.prop)">
            <el-select v-model="editform.status">
              <el-option label="启用" value="1" />
              <el-option label="禁止" value="0" />
            </el-select>
          </template>
          <!-- 文本域 -->
          <template v-else-if="['route_descripition'].includes(item.prop)">
            <el-input v-model="editform[item.prop]" :rows="8" type="textarea" />
          </template>
          <!-- 输入框 -->
          <template v-else>
            <el-input v-model="editform[item.prop]" :readonly="item.isReadonly ? item.isReadonly : false" />
          </template>

        </cy-form-item>
        <cy-form-item>
          <!-- 操作按钮 -->
          <el-button type="primary" @click="EditSubmit">确认</el-button>
          <el-button @click="editdrawer = false">取消</el-button>
        </cy-form-item>
      </cy-form>
    </el-drawer>
    <!-- 添加抽屉 -->
    <el-drawer v-model="adddrawer" title="edit" :with-header="false">
      <cy-form class="EditForm" label-width="auto" style="max-width: 31.25rem">
        <cy-form-item v-for="(item, index) in addFormColumns" :key="index" :label="item.label">
          <!--状态选择 -->
          <template v-if="['status'].includes(item.prop)">
            <el-select v-model="addform.status">
              <el-option label="启用" value="1" />
              <el-option label="禁止" value="0" />
            </el-select>
          </template>
          <!-- 输入框 -->
          <template v-else>
            <el-input v-model="addform[item.prop]" :readonly="item.isReadonly ? item.isReadonly : false" />
          </template>
        </cy-form-item>
        <cy-form-item>
          <el-button type="primary" @click="AddSubmit">确认</el-button>
          <el-button @click="adddrawer = false">取消</el-button>
        </cy-form-item>
      </cy-form>
    </el-drawer>
  </div>
</template>

<script lang="tsx" setup>
import { ref, reactive, watch, onMounted } from "vue";
import type { TableInstance } from "element-plus";

import CyTable from "@/components/table";
import CyForm from "@/components/form";
import CyFormItem from "@/components/form-item";

import { ElMessage, ElMessageBox, VLoad } from "element-plus";
import { Search, Plus } from "@element-plus/icons-vue";
import {
  getRouteAllAPI,
  getRoutePageAPI,
  getRouteKeyPageAPI,
  UpdateRouteByIdAPI,
  DeleteRouteByIdAPI,
  DeleteRouteMoreByIdAPI,
  AddRouteAPI,
} from "@/api/route";
import { assignObject } from "@/utils/object";

const tableData = ref([]);
const tableRef = ref<TableInstance>();
const loading = ref(true);
const multipleSelection = ref([]);
const editdrawer = ref(false);
const adddrawer = ref(false);
const page = reactive({
  currentPage: 1,
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
// 筛选
const SearchKeyWord = reactive({
  selectKey: "route_id",
  searchValue: "",
});
// 表格配置
const ruleTable = reactive({
  columns: [
    // 全选框列
    {
      type: "selection",
      width: 55,
    },
    // 数据列
    { prop: "route_id", label: "路由ID", align: "center" },
    { prop: "route_name", label: "路由名", align: "center" },
    { prop: "route_path", label: "路由路径", align: "center" },
    // 状态列
    {
      prop: "status",
      label: "状态",
      align: "center",
      render: ({ row }) => (
        <span class={ClStatus(row.status)}>
          {row.status === "1" ? "启用" : "禁用"}
        </span>
      ),
    },
    // 操作列
    {
      label: "操作",
      align: "center",
      headerRender: () => (
        <div style="text-align: center;">
          <div class="OptionsBtn" onClick={MoreDelete} style="display: inline-block;">
            批量删除
          </div>
        </div>
      ),
      render: ({ row, index }) => (
        <div>
          <el-button onClick={() => handleEdit(index, row)}>修改</el-button>
          <el-button type="danger" onClick={() => handleDelete(index, row)}>
            删除
          </el-button>
        </div>
      ),
    },
  ],
});
// 分页查询
const getRoutePage = () => {
  loading.value = true;
  getRoutePageAPI({
    page: page.currentPage,
    pageSize: page.pageSize,
    orderBy: "route_id ASC",
  })
    .then((res) => {
      const { row, total } = res.data;
      tableData.value = row;
      page.total = total;
    })
    .finally(() => (loading.value = false));
};
// 选择框选中
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

/* 修改 */
const editform = reactive({
  route_id: '',
  route_name: '',
  route_path: '',
  status: '',
});
const editFormColumns = [
  { prop: "route_id", label: "路由ID" },
  { prop: "route_name", label: "路由名" },
  { prop: "route_path", label: "路由路径" },
  { prop: "status", label: "状态" },
];
const handleEdit = (index: number, row: any) => {
  assignObject(editform, row);
  editdrawer.value = true;
};
// 确认修改提交
const EditSubmit = () => {
  // 提交后台
  UpdateRouteByIdAPI(editform).then((res) => {
    const { code, message } = res.data;
    if (!SearchKeyWord.searchValue) {
      getRoutePage();
    } else {
      SearchRouteList()
    }
    ElMessage.success(message);
    editdrawer.value = false;
  });
};
/* 添加 */
const addform = reactive({
  route_id: '',
  route_name: '',
  route_path: '',
  status: '',
});
const addFormColumns = [
  { prop: "route_id", label: "路由ID" },
  { prop: "route_name", label: "路由名" },
  { prop: "route_path", label: "路由路径" },
  { prop: "status", label: "状态" },
];
// 添加任务
const handleAdd = () => {
  adddrawer.value = true;
};
// 确认添加提交
const AddSubmit = () => {
  AddRouteAPI(addform).then((res) => {
    const { code, message } = res.data;
    ElMessage.success(message);
    getRoutePage();
    adddrawer.value = false;
  });
};
/* 删除 */
const handleDelete = (index: number, row: any) => {
  // 警告提示
  ElMessageBox.confirm("删除操作无法撤回，是否继续?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(() => {
      // 执行删除
      DeleteRouteByIdAPI(row.route_id).then((res) => {
        const { code, message } = res.data;
        getRoutePage();
        ElMessage.success(message);
      });
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: "info",
        message: "取消删除操作",
      });
    });
};
const MoreDelete = () => {
  if (!multipleSelection.value || multipleSelection.value.length === 0) {
    ElMessage.warning("未选择目标");
    return;
  }
  const ids = multipleSelection.value.reduce(
    (acc, item) => [...acc, item.route_id],
    []
  );
  // 警告提示
  ElMessageBox.confirm("删除操作无法撤回，是否继续?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(() => {
      // 执行删除
      DeleteRouteMoreByIdAPI(ids).then((res) => {
        const { code, message } = res.data;
        getRoutePage();
        ElMessage.success(message);
      });
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: "info",
        message: "取消删除操作",
      });
    });
};

/* 查询 */
const SearcSelect = [
  { prop: "route_id", label: "路由ID" },
  { prop: "route_name", label: "路由名" },
  { prop: "route_path", label: "路由路径" },
  { prop: "status", label: "状态" },
];
const SearchRouteList = () => {
  if (!SearchKeyWord.searchValue) {
    getRoutePage();
    return;
  }
  loading.value = true;
  getRouteKeyPageAPI({
    SearchKey: SearchKeyWord.selectKey,
    SearchValue: SearchKeyWord.searchValue,
    page: page.currentPage,
    pageSize: page.pageSize,
    orderBy: "route_id ASC",
  })
    .then((res) => {
      const { row, total } = res.data;
      tableData.value = row;
      page.total = total;
    })
    .finally(() => (loading.value = false));
};
// 状态动态类名
const ClStatus = (Status: string) => {
  switch (Status) {
    case "1":
      return "status-active";
    default:
      return "status-unactive";
  }
};
// 监听分页
watch(
  () => page.currentPage,
  () => {
    if (!SearchKeyWord.searchValue) {
      getRoutePage();
    } else {
      SearchRouteList()
    }
  }
);
onMounted(() => {
  setTimeout(() => {
    getRoutePage();
  }, 1000);
});
</script>
<style scoped lang="scss">
.Box {
  position: relative;

  .SearchBox {
    width: 100%;
    height: 60px;
    background-color: #fff;
    border-bottom: 1px solid #eee;

    .el-input {
      width: 350px;
      margin-left: 0.5rem;
    }

    .searchBtn {
      color: rgb(15, 153, 245);
    }

    .addBtn {
      margin-right: 1rem;
    }
  }

  .PageBox {
    background-color: #fff;
    padding-left: 30%;
    margin: 1rem;
  }

  .TableBox {
    .Table {
      width: 100%;
      min-height: 25rem;
      border-top: 1px solid #eee;
    }

    :deep(.status-active) {
      color: green;
      font-weight: 600;
    }

    :deep(.status-unactive) {
      color: #f56c6c;
      font-weight: 600;
    }

    :deep(.OptionsBtn) {
      height: 30px;
      line-height: 30px;
      width: 8.125rem;
      border: 1px solid #f56c6c;
      border-radius: 0.3rem;
      text-align: center;
      background-color: #f56c6c;
      color: #fff;
      cursor: pointer;

      &:hover {
        background-color: #e78d8d;
        border: 1px solid #e78d8d;
      }
    }
  }

  .EditForm {
    :deep(.el-form-item__content) {
      display: flex;
      justify-content: center;
      align-content: center;
    }
  }
}
</style>
